package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.ComplaintLog;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.ComplaintReportLogService;
import com.ugoodtech.mdcc.core.domain.ComplaintReportLog;
import com.ugoodtech.mdcc.core.domain.QComplaintReportLog;
import com.ugoodtech.mdcc.core.repository.ComplaintReportLogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class}, propagation = Propagation.REQUIRED)
@Slf4j
public class ComplaintReportLogServiceImpl implements ComplaintReportLogService {

    @Autowired
    private ComplaintReportLogRepository complaintReportLogRepository;

    @Override
    public JsonResponse getLogList(Long complaintReportId, Pageable pageable) {
        QComplaintReportLog qComplaintReportLog = QComplaintReportLog.complaintReportLog;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qComplaintReportLog.deleted.eq(false));
        builder.and(qComplaintReportLog.enabled.eq(true));
        builder.and(qComplaintReportLog.complaintReportId.eq(complaintReportId));
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ComplaintReportLog> complaintReportList = complaintReportLogRepository.findAll(builder, pageable);
        log.info("complaintReportList, {]", complaintReportList);
        List<ComplaintLog> logList = getResponse(complaintReportList.getContent());
        Page<ComplaintLog> page = new PageImpl(logList, pageable, complaintReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 获取投诉单历史记录
     *
     * @param complaintReportList
     * @return
     */
    private List<ComplaintLog> getResponse(List<ComplaintReportLog> complaintReportList) {
        log.info("complaintReportList {}", complaintReportList);
        List<ComplaintLog> logList = new ArrayList<>();
        for (ComplaintReportLog reportLog : complaintReportList) {
            ComplaintLog log = new ComplaintLog();
            BeanUtils.copyProperties(reportLog, log);
            logList.add(log);
        }
        return logList;
    }


}
